<?php

namespace app\common\business;

use \think\Request;
use \think\Session;
use app\common\mysql\Users as usersMysql;
use app\common\business\user\Point as pointBn;
class Match extends \app\common\business\AbstractModel {

    /**
     * 会员列表
     * page
     * count
     * need_total
     */
    public static function matchlist($params, $user_id = '') {
        self::_checkPageAndCount($params); 
        $time=time();
        $listdata = usersMysql::name('match')
                ->field('match_id,home_id,home_team,home_logo,guest_id,guest_team,guest_logo,status,match_time,sale_time')
                ->whereTime('match_time', '>=', $time)
                ->order('match_time asc')
                ->limit($params['offset'], $params['count'])
                ->select();
        if (!empty($listdata)) {
            $listdata = self::_adapterList($listdata,$user_id);
        }
        if (isset($params["need_total"]) && $params["need_total"] == 1) {
            return array("listdata" => $listdata, "total" => self::total($params));
        }
        return array("listdata" => $listdata);
    }

    /**
     * 获取Query条件
     *
     * @param array $params
     * @return array
     */
    protected static function _getQuery($params) {
        $query = array();
        if (isset($params["type"])) {
            $query['type'] = $params["type"];
        }
        return $query;
    }

    /**
     * 适配输出
     *
     * @params
     * @return array
     */
    protected static function _adapterList($result, $user_id = '') {
        foreach ($result as $k => $v) {

            $result[$k]['home_logo'] = "http://sjbimg.qiu7.net/" . $v['home_logo'];
            $result[$k]['guest_logo'] = "http://sjbimg.qiu7.net/" . $v['guest_logo'];
            //用户，判断 是否已答题 
            $result[$k]['ask_status'] = 0;
            if ($user_id) {
                $status = usersMysql::name('match_answer')->where(array('user_id' => $user_id, 'match_id' => $v['match_id']))->count();
                if ($status > 0) {
                    $result[$k]['ask_status'] = 1;
                }
            }
        }

        return $result;
    }

    /**
     * 会员列表
     * page
     * count
     * need_total
     */
    public static function sjbsclist($params) {
        self::_checkPageAndCount($params);
        $listdata = usersMysql::name('match')
                ->field('match_id,home_id,home_team,home_logo,guest_id,guest_team,guest_logo,status,match_time,sale_time')
                ->order('match_time asc')
                ->limit($params['offset'], $params['count'])
                ->select();
        if (!empty($listdata)) {
            foreach ($listdata as $k => $v) {
                $listdata[$k]['home_logo'] = "http://sjbimg.qiu7.net/" . $v['home_logo'];
                $listdata[$k]['guest_logo'] = "http://sjbimg.qiu7.net/" . $v['guest_logo'];
                if($v['match_time']>time()){
                    $listdata[$k]['match_status']=0;
                }elseif($v['match_time']>time() &&$v['match_time']+2*3600<=time()){
                     $listdata[$k]['match_status']=1;//比赛进行中
                }else{
                      $listdata[$k]['match_status']=2;//比赛结束
                }
            }
        }
        if (isset($params["need_total"]) && $params["need_total"] == 1) {
            return array("listdata" => $listdata, "total" => self::total($params));
        }
        return array("listdata" => $listdata);
    }

    /**
     * 获取where条件
     *
     * @param array $params
     * @return array
     */
    protected static function _getWhere($params) {
        if (isset($params["user_id"])) { //今天
            $where['user_id'] = $params["user_id"];
        }
        if (isset($params["status"])) { //今天
            $where['status'] = $params["status"];
        }
        //  $where = '1=1  ';
        /*
          if (isset($params["type"]) && $params['type'] == 1) { //今天
          $time = strtotime(date("Y-m-d"));
          $time2 = strtotime(date("Y-m-d 23:59:59"));
          $where.=" and  sale_time  between " . $time . " AND " . $time2;
          } else if (isset($params["type"]) && $params['type'] == 2) { //明日
          $time = strtotime(date('Y-m-d', strtotime('+1 day')));
          $time2 = strtotime(date("Y-m-d 23:59:59", strtotime('+1 day')));
          $where.=" and  sale_time  between " . $time . " AND " . $time2;
          } */
        // $where = 'status=1';
        return $where;
    }

    /**
     * 计算总数
     *
     * @param array $params
     * @return int
     */
    public static function total($params) {
        $where = self::_getWhere($params);
        $count = usersMysql::name('guess')
                ->where($where)
                ->count();
        return $count;
    }

    /**
     * 答案内容
     * page
     * count
     * need_total
     */
    public static function askshow($params) {
        $matchinfo = usersMysql::name('match')->where(array('match_id' => $params['match_id']))->find();

        if ($matchinfo['status'] == 0) {
            exception('当前比赛简答题未开放', 10000003);
        } elseif ($matchinfo['status'] == 2) {
            exception('当前比赛简答题已关闭', 10000003);
        }
        $matchinfo['home_logo'] = "http://sjbimg.qiu7.net/" . $matchinfo['home_logo'];
        $matchinfo['guest_logo'] = "http://sjbimg.qiu7.net/" . $matchinfo['guest_logo'];

        $listdata = usersMysql::name('match_ask')
                ->field('ask_id,match_id,ask_title,ask_content,ask_sort,ask_point')
                ->where(array('match_id' => $params['match_id']))
                ->order('ask_sort desc')
                ->select();
        if ($listdata) {
            foreach ($listdata as $k => $v) {
                $ask_content = explode(";", $v['ask_content']);
                $listdata[$k]['ask_content'] = $ask_content;
            }
        }
        return array("listdata" => $listdata, 'matchinfo' => $matchinfo);
    }

    /**
     * 用户答题 
     * match_id
     * answer[]
     * ask_id,answer_content
     * user_id
     */
    public static function addanswer($params) {
        if (!isset($params['answer'])) {
            exception('答题内容不能为空', 1000004);
        }
        if (!isset($params['match_id']) || empty($params['match_id'])) {
            exception('答题不完善', 1000004);
        }
        $matchinfo = usersMysql::name('match')->where(array('match_id' => $params['match_id']))->find();

        if ($matchinfo['status'] == 0) {
            exception('当前比赛简答题未开放', 10000003);
        } elseif ($matchinfo['status'] == 2) {
            exception('当前比赛简答题已关闭', 10000003);
        }
        $ask_id_arr = usersMysql::name('match_ask')->where(array('match_id' => $params['match_id']))->column('ask_id');

        //用户是否已答过了
        $answeredcount = usersMysql::name('match_answer')->where(array('match_id' => $params['match_id'], 'user_id' => $params['user_id']))->count();
        if ($answeredcount >= 1) {

            exception('今日答题已完成，答案敬请期待', 1000004);
        }
        $insertdata = array();
        $temp = array();
        $time = time();
        foreach ($params['answer'] as $k => $v) {
            // $v = json_decode($v, true);
            if (!in_array($v['ask_id'], $ask_id_arr)) {
                exception('答题参数不正确', 1000004);
            }
            $temp['ask_id'] = $v['ask_id'];
            $temp['answer_content'] = $v['answer_content'];
            $temp['user_id'] = $params['user_id'];
            $temp['match_id'] = $params['match_id'];
            $temp['add_time'] = $time;
            $insertdata[] = $temp;
        }
        $r = usersMysql::name('match_answer')->insertAll($insertdata);
        if ($r == true) {
            $data['next_id'] = self::todaynoguess($params);
            return $data;
        }
        exception('答题失败', 1000004);
    }

    /**
     * 我的答题 
     */
    public static function myanswer($params) {
        self::_checkPageAndCount($params);
        $where = self::_getWhere($params);
        $listdata = usersMysql::name('match_answer')
                ->field('match_id,user_id,ask_id,answer_content')
                ->where($where)
                ->group('match_id')
                ->order('add_time desc')
                ->limit($params['offset'], $params['count'])
                ->select();
        if (!empty($listdata)) {
            $listdata = self::_adaptermyanswerList($listdata);
        }
        if (isset($params["need_total"]) && $params["need_total"] == 1) {
            return array("listdata" => $listdata, "total" => self::total($params));
        }
        return array("listdata" => $listdata);
    }

    /**
     * 适配输出
     *
     * @params
     * @return array
     */
    protected static function _adaptermyanswerList($result) {
        foreach ($result as $k => $v) {
            //球队信息
            $matchinfo = usersMysql::name('match')->where(array('match_id' => $v['match_id']))->find();
            $result[$k]['home_team'] = $matchinfo['home_team'];
            $result[$k]['home_logo'] = "http://sjbimg.qiu7.net/" . $matchinfo['home_logo'];
            $result[$k]['guest_team'] = $matchinfo['guest_team'];
            $result[$k]['guest_logo'] = "http://sjbimg.qiu7.net/" . $matchinfo['guest_logo'];
            $result[$k]['match_time'] = $matchinfo['match_time'];
            $result[$k]['status'] = $matchinfo['status'];
            //答题
            $result[$k]['right'] = 0;
            $result[$k]['error'] = 0;
            $result[$k]['point'] = 0;
            if ($v['status'] == 3) {
                $asklist = usersMysql::name('match_answer')->alias('ma')->field('status,(select ask_point from clt_match_ask  as mask where mask.ask_id=ma.ask_id) as point')->where(array('match_id' => $v['match_id']))->select();
                foreach ($asklist as $kk => $vv) {
                    if ($vv['status'] == 1) {
                        $result[$k]['right'] = $result[$k]['right'] + 1;
                        $result[$k]['point'] = $result[$k]['point'] + $vv['point'];
                    } else if ($vv['status'] == 2) {
                        $result[$k]['error'] = $result[$k]['error'] + 1;
                    }
                }
            }
        }

        return $result;
    }

    /**
     * 答题详情
     */
    public static function myanswershow($post) {

        $listdata = usersMysql::name('match_answer')->alias('ma')->field('status,answer_content,(select ask_title from clt_match_ask  as mask where mask.ask_id=ma.ask_id) as ask_title,(select ask_content from clt_match_ask  as mask where mask.ask_id=ma.ask_id) as answer_content_str')->where(array('match_id' => $post['match_id'], 'user_id' => $post['user_id']))->select();
        foreach ($listdata as $kk => $vv) {
            $str = explode(";", $vv['answer_content_str']);
            $listdata[$kk]['answer_content'] = $str[$vv['answer_content']];
        }
        return array("listdata" => $listdata);
    }

    /**
     * 今日答题 是否全部答过
     * user_id
     */
    public static function checktodyguess($post) {
        $total = usersMysql::name('match')->where(array('status' => 1))->count();
        $time  = strtotime(date("Y-m-d"));
        $time2 = strtotime(date("Y-m-d 23:59:59"));
        $where = ' user_id=' . $post['user_id'] . " and   add_time  between " . $time . " AND " . $time2;
        $total2 = usersMysql::name('match_answer')
                ->where($where)
                ->group('match_id')
                ->order('add_time desc')
                ->select();
         if (count($total2) == $total && $total > 0) {
            return true;
        } else {
            return false;
        }
    }

    /*
     * 今天 还没答题的
     */

    public static function todaynoguess($post) {
        $match_id = usersMysql::name('match')->where(array('status' => 1))->column('match_id');
        $time = strtotime(date("Y-m-d"));
        $time2 = strtotime(date("Y-m-d 23:59:59"));
        $where = ' user_id=' . $post['user_id'] . " and   add_time  between " . $time . " AND " . $time2;
        $data = usersMysql::name('match_answer')
                ->where($where)
                ->group('match_id')
                ->order('add_time desc')
                ->column('match_id');
        foreach ($match_id as $v) {
            if (!in_array($v, $data)) {
                return $v;
            }
        }
        return '';
    }
    /*
     * 计算积分
     */

    public static function sumAskPoint($post) {
        $panduan=true;
        foreach($post as $key=>$val){
            usersMysql::startTrans();
            $matchinfo=usersMysql::name('match')->where(array('match_id' => $val))->update(array('status' => 3,'update_time'=>time()));

            $askinfo=usersMysql::name('match_ask')->where(array('match_id' => $val))->select();
            foreach($askinfo as $k=>$v){
                $r2=true;
                $answerinfo=usersMysql::name('match_answer')->where(array('ask_id' => $v['ask_id']))->find();
                if($v['ask_result']==$answerinfo['answer_content']){
                    $answerpost['status']=1;

                    $point['user_id']=$answerinfo['user_id'];
                    $point['point']  =$v['ask_point'];
                    $point['source_type']=0;
                    $point['change_type']=1;
                    $point['point_type'] =5;
                    $point['change_memo']=' 竞彩成功获得'.$v['ask_point'].'积分';
                    $r2=pointBn::updatePoint($point);
                }else{
                    $answerpost['status']=2;

                }

                $r=usersMysql::name('match_answer')->where(array('answer_id'=>$answerinfo['answer_id']))->update($answerpost);
                if($r==true&&$r2==true){
                    $panduan=true;
                }else{
                    return false;
                }
            }
        }
        if($panduan){
            usersMysql::commit();
            return true;
        }else{
            usersMysql::rollback();
            return false;
        }
    }

}
